#include "Unit.h"

Unit::Unit(Map &map) : map(map) {
    x = 0;
    y = 0;
    health = 1;
    dir = DIR_E;
}


Unit::~Unit() {
}

int Unit::GetTileX() {
    return x;
}

int Unit::GetTileY() {
    return y;
}

void Unit::SetDirection(int newDir) {
    dir = newDir;
}
void Unit::RotateCW() {
    dir++;
    if (dir > DIR_SE) dir = DIR_S;
}
void Unit::RotateCCW() {
    dir--;
    if (dir < DIR_S) dir = DIR_SE;
}

void Unit::Move(int newX, int newY) {
    x = newX;
    y = newY;
}

void Unit::Attack(int x, int y) {
    Unit *unit = map.GetTileUnit(x, y);
    if (unit != NULL) { 
        unit->TakeDamage(1);
    }
}

void Unit::TakeDamage(int damage) {
    if (health > 0) {
        health -= damage;
        if (health <= 0) {
            Die();
        }
    }
}

std::vector<Vector2i> Unit::GetActions(int actionType) {
    std::vector<Vector2i> actions;
    return actions;
}

void Unit::DoAction(int actionType, int tileX, int tileY) {
    if (actionType == ACT_MOVE) {
        Move(tileX, tileY);
    }
    else if (actionType == ACT_ATTACK) { 
        Attack(tileX, tileY);
    }
    else if (actionType == ACT_ROTATE) {
        const int directions[3][3] = {{3,2,1}, {4,0,0}, {5,6,7}};
        SetDirection(directions[tileX - x + 1][tileY - y + 1]);
    }
}

void Unit::Die() {
    std::cout << "I am dead" << std::endl;
    // do some animation
}

void Unit::Update(float dt) {
    // do things
}

void Unit::Render(SpriteManager &spriteManager) {
    sprites[dir].SetPosition(x*TILE_SIZE, y*TILE_SIZE);
    spriteManager.Draw(sprites[dir]);
}
